import { useUserStore } from "@/store";
import { getToken } from "@/utils/auth";
import { Message } from "@arco-design/web-vue";

export default function useConnection(streamCallback, rttCallback, orientationCallback, closeLoading) {
  let pc = null;
  let pendingCandidates = [];
  let remoteDescSet = false;
  const userStore = useUserStore();
  let token = getToken();
  if (!token) {
    Message.error("请先登录");
    userStore.logout()
    return {}
  }
  const signalingServerUrl = `${import.meta.env.VITE_WS_BASE_URL}/caller/websocket?Authorization=${token}`;
  const ws = new WebSocket(signalingServerUrl);

  const startJoin = (inviteCode:string) => {
    ws.send(JSON.stringify({ type: 'join', data: inviteCode }));
  };

  const sendOpr = (opr: string) => {
    ws.send(JSON.stringify({ type: 'opr', data: opr }));
  }

  const startWebRTC = async () => {
    pc = new RTCPeerConnection({
      iceTransportPolicy: "relay",
      iceServers: [
        // 可配置 STUN/TURN 服务器
        {
          urls: 'turn:stun.zhikayun.com:3478',
          username: 'admin',
          credential: '123456'
        }
      ],
    });

    pc.onicecandidate = (event) => {
      if (event.candidate) {
        console.log('local:', event.candidate.candidate);
        ws.send(JSON.stringify({ type: 'ice', data: event.candidate }));
      } else {
        console.log('All ICE candidates have been sent');
      }
    };

    pc.oniceconnectionstatechange = () => {
      console.log('ICE Connection State:', pc.iceConnectionState);
    };

    pc.onicecandidateerror = (event) => {
      console.error('ICE Candidate Error:', event);
      closeLoading()
    };

    pc.ontrack = (event) => {
      streamCallback(event.streams[0]);
    };

    pc.addTransceiver('video', { direction: 'recvonly' });

    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    ws.send(JSON.stringify({ type: 'sdp', data: offer }));
  };
  ws.onopen = () => {
    console.log('WebSocket 已连接');
  };

  ws.onclose = () => {
    console.log("Websocket 已关闭")
    closeLoading()
  }

  ws.onerror = () => {
    closeLoading()
  }

  ws.onmessage = async (event) => {
    const msg = JSON.parse(event.data);
    switch (msg.type) {
      case 'feedback':{
        if (msg.data.code === 200) {
          startWebRTC();
        } else {
          Message.warning(msg.data.message)
          closeLoading()
        }
        break;
      }
      case 'sdp':{
        await pc.setRemoteDescription(new RTCSessionDescription(msg.data));
        remoteDescSet = true;
        pendingCandidates.forEach(candidate => {
          pc.addIceCandidate(new RTCIceCandidate(candidate))
        })
        pendingCandidates = [];
        break;
      }
      case 'ice':{
        const candidate = new RTCIceCandidate(msg.data);
        if (remoteDescSet) {
          await pc.addIceCandidate(candidate);
        } else {
          pendingCandidates.push(candidate);
        }
        break;
      }
      // 该分支主要是对 失败条件进行判断
      case 'oprcallback':{
        Message.error(msg.data.msg)
        break;
      }
      case 'orientation':{
        orientationCallback(msg.data)
        break;
      }
      default:{
        break;
      }
        
    }
  };

  const getCurrentRTT = async () => {
    const stats = await pc.getStats();
    let selectedCandidatePairId = null;

    stats.forEach((report) => {
      if (report.type === 'transport') {
        selectedCandidatePairId = report.selectedCandidatePairId;
      }
    });

    stats.forEach((report) => {
      if (report.id === selectedCandidatePairId && report.currentRoundTripTime) {
        const rtt = report.currentRoundTripTime;
        rttCallback((rtt * 1000).toFixed(2))
      }
    });
  };

  let rttInterval = setInterval(() => {
    if (pc) getCurrentRTT();
  }, 3000);

  const closeWebrtc = () => {
    if (pc) {
      // pc.getSenders().forEach(sender => pc.removeTrack(sender)); // 移除所有 track
      pc.close();     // 正式关闭连接
      pc = null;      // 清除引用，避免内存泄漏
      clearInterval(rttInterval);
      console.log("PeerConnection 已关闭");
    }
    if (rttInterval) {
      clearInterval(rttInterval);
      rttInterval = null;
      console.log("RTT 定时器已清除");
    }
  }

  const closeConnection = () => {
    ws.close()
    ws = null;
    closeWebrtc()
  }

  return {
    closeConnection,
    closeWebrtc,
    startJoin,
    sendOpr
  }
}